<?php

namespace app\admin\controller;

class Setview extends base
{
    //文件目录
    private $dir;
    //文件路径
    private $fileroot;
    private $dirname;
    private $editExt;

    public function _initialize()
    {
        //读取模板目录
        //         $this->dir = APP_PATH . $this->request->param('type').'/view/';
        //        $this->fileroot = $this->dir . $this->request->param('dir') . '/' . $this->request->param('name');
        $this->dirname = $this->request->param('dir');

        $this->dir = ROOT_PATH . 'template' . DS . $this->request->param('type') . DS . $this->dirname . DS;
        $this->fileroot = $this->dir . $this->request->param('name');
        $this->editExt = array('html', 'js', 'css', 'txt');
    }

    /**
     * 读取文件目录
     * @param $basedir 文件地址
     */
    function checkdir($basedir)
    {
        static $filename = array();
        if ($dh = opendir($basedir)) {
            while (($file = readdir($dh)) !== false) {
                $tmparray = explode('.html', $file);
                if ($file != '.' && $file != '..' && count($tmparray) > 1) {

                    if (!is_dir($basedir . "/" . $file)) {
                        $filename[] = ['filename' => "$file", 'type' => $this->request->param('type'), 'dir' => $this->request->param('dir'), 'name' => $file];
                        //"filename: $dir/$file <br>";
                    } else {
                        $dirname = $basedir . "/" . $file;
                        $this->checkdir($dirname);
                    }
                }
            }
        }
        return $filename;
    }

    /**
     * 选择模板
     */
    public function xuanze()
    {
        $this->assign('dirlist', templateList($this->request->param('type')));
        $this->assign('type', $this->request->param('type'));
        return $this->fetch();
    }

    /**
     * 新版
     */
    public function index()
    {
        $dirlist = array();
        $dir = cache($this->request->param('dir'));
        if (empty($dir)) {
            $flag = \FilesystemIterator::KEY_AS_FILENAME;
            $files = new \FilesystemIterator($this->dir, $flag);
            foreach ($files as $finfo) {
                if (!($finfo->isDir())) {
                    $dirlist[] = array(
                        'date' => date("Y-m-d", $finfo->getMTime()),
                        'type' => $finfo->getExtension(),
                        'size' => number_format($finfo->getSize()), //文件大小
                        'name' =>  $finfo->getFileName() //文件名称
                    );
                }
            }
            cache($this->request->param('dir'), $dir, 240);
        }

        $this->assign('dirlist', $dirlist);
        return $this->fetch();
    }


    /**
     * 旧版
     */
    public function index_old()
    {
        /*
        $flag = \FilesystemIterator::KEY_AS_FILENAME;
        $files = new \FilesystemIterator($this->fileroot);
        foreach($files as $finfo)
        {
            if (!($finfo->isDir())) {

                echo "<br/>".$finfo->getExtension();
                $finfo->isDir()?"<DIR>":"";
                number_format($finfo -> getSize());//文件大小
            echo $finfo->getFileName()."\n";//文件名称
            }
        }*/
        //全模板路径
        //APP_PATH.request()->module().'/view/'.$this->request->controller().'_'.$this->request->action().'.'.config('template.view_suffix')
        $html = '';
        if ($this->request->param('name')) {
            $fp = fopen($this->fileroot, 'r') or die("无法打开文件！");
            if (filesize($this->fileroot)) {
                $html = fread($fp, filesize($this->fileroot));
                fclose($fp);
            }
            $this->assign('value', $html ? $html : '');
        }
        $dir = cache($this->request->param('dir'));
        if (empty($dir)) {
            $dir = $this->checkdir($this->dir);
            cache($this->request->param('dir'), $dir, 240);
        }
        $this->assign('dirlist', $dir);
        $this->assign('dir', $this->request->param('dir'));
        $this->assign('type', $this->request->param('type'));
        $this->assign('dirfile', $this->request->param('name'));

        return $this->fetch();
    }

    /**
     * 编辑
     */
    public function edit($id = null)
    {
        if (!empty($this->request->param('name'))) {
            $html = null;
            $fp = fopen($this->fileroot, 'r') or die("无法打开文件！");
            if (filesize($this->fileroot)) {
                $html = fread($fp, filesize($this->fileroot));
                fclose($fp);
            }
            $this->assign('value', $html);
        }
        $this->assign('editExt',implode(' | ', $this->editExt));
        return $this->fetch();
    }

    /**
     * 保存
     */
    public function save()
    {
        $data = $this->request->param();

        if (!$this->request->isPost() || empty($data['filevalue'])) {
            return ajax_info('请检测模板不能为空');
            // exit();
            // $this->error('请检测模板不能为空');
        }

        if (empty($data['name'])) {
            return ajax_info('文件名不能为空');
            exit();
        }

        $path_parts  = pathinfo($data['name']);
        /*允许编辑的文件类型*/
        if (empty($path_parts['extension'])||!in_array($path_parts['extension'], $this->editExt)) {
            return ajax_info('只允许操作文件类型如下：' . implode('|', $this->editExt));
            exit();
        }
        /*--end*/

        $myfile = fopen(rtrim($this->fileroot, '/'), "w") or die("无法打开文件！");
        $filevalue = html_entity_decode($data['filevalue']);

        fwrite($myfile, $filevalue);
        fclose($myfile);
        return ajax_info('保存模板成功', 'index');

        //        $this->success('修改模板成功！');
    }
}
